import 'dart:developer';
// ignore: deprecated_member_use
import 'dart:html' as html;
import 'dart:typed_data';


import 'package:dio/dio.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key,required this.userInfo});
  Map userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
   Map userInfo = {
    "id":"",
    "avatar": null,
    "nickName": null,
  };

  final TextEditingController _avatarController = TextEditingController();
  // 更新昵称
updateNickName() async {
  log(_avatarController.text);
    if (_avatarController.text.isEmpty) {
      return ToastUtil.showError('昵称不能为空!');
    }
    if(_avatarController.text.length >10){
      return ToastUtil.showError('昵称不能超过10个字符!');
    }
    try {
      //await http.put('/userInfo',data:{'nickName':nickName})
      await http.put('/userInfo', {"nickName": _avatarController.text});
      setState(() {
        userInfo['nickName'] = _avatarController.text;
        ToastUtil.showSuccess('修改成功!');
      });
    } catch (e) {
      return ToastUtil.showError('网络异常!');
    }
}
// 上传头像
void uploadAvatar(){
  showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    _pickImageCamera();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    _pickImageFromGallery();
                  },
                )
              ]));
        });
}
//调用相机
Future<void> _pickImageCamera() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.camera);
    if (pickedFile != null) {
      ToastUtil.showSuccess(pickedFile.path);
    }
}
// 从相册选择图片
Future<void> _pickImageFromGallery() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    
    if (pickedFile != null) {
      ToastUtil.showSuccess(pickedFile.path);
      try {
        // 获取 blob URL
        String blobUrl = pickedFile.path;
        // 从 blob URL 获取字节数据
        html.HttpRequest request = await html.HttpRequest.request(blobUrl, method: 'GET', responseType: 'arraybuffer');
        Uint8List fileBytes = Uint8List.view(request.response);
        // 获取文件名
        String fileName = 'image_${DateTime.now().millisecondsSinceEpoch}.jpg';
        
        FormData formData = FormData.fromMap({
          "file": MultipartFile.fromBytes(fileBytes, filename: fileName),
          //"file": await MultipartFile.fromFile(pickedFile.path),
          "type": "avatar",
        });
        var res = await http.post('/upload', formData);
        if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
        setState(() {
          userInfo['avatar'] = res['data']['url'];
        });
      } finally {
        eventBus.fire(BackMineEvent());
        Navigator.pop(context);
      }
    }
  }
  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _avatarController.text = userInfo['nickName']??'';
    });
  }
  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop:false,
      child:Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(
    onPressed: () {
      eventBus.fire(BackMineEvent());
      Navigator.pop(context);
    },
    icon: const Icon(Icons.arrow_back),
  ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap:(){
                        uploadAvatar();
                      },
                      child:ClipRRect(
                      borderRadius: BorderRadius.circular(50.0),
                      child: userInfo['avatar'] != null
                            ? Image.network(userInfo['avatar'],
                                width: 30, height: 30)
                            : Image.asset('images/avatar_1.jpg',
                                width: 30, height: 30)
                      // child: Image.asset(
                      //   'images/avatar_1.jpg',
                      //   width: 30,
                      //   height: 30,
                      // ),
                    ),
                    ),
                    
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              Text('昵称'),
              Spacer(),
              Expanded(
                child: TextField(
                  controller: _avatarController,
                  decoration: InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                  // 点击完成按钮时触发
                  onEditingComplete: () {
    updateNickName();
  }
                ),
              ),
              Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    )
    );
  }
}
